<?php
/**
 * 短信发送接口
 *
 * @author    zhli<zhli@vip.deyi.com>>
 * @since     2015/6/3 11:30
 * @copyright deyi.com
 */

namespace Deyi\Functions;

/**
 * Class SendSmsFunction
 * @package Deyi\Functions
 */
class SendSmsFunction
{

    /**
     * 向指定手机号发送短信
     *
     * @author liang<lang@vip.deyi.com>
     * @param $mobile
     * @param $message
     * @return bool
     */
    public static function sendMessage($mobile, $message)
    {
        $post = '';
        foreach ([
                     'channel' => 'api',
                     'pwd' => 'Uo@bn8ML',
                     'mobile' => $mobile,
                     'message' => $message,
                 ] as $k => $v) {
            $post .= "&$k=$v";
        }

        $post = substr($post, 1);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "http://pm.deyi.com");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        curl_setopt($ch, CURLOPT_TIMEOUT, 3);

        $return = curl_exec($ch);
        curl_close($ch);

        $jsonArray = json_decode($return);
        if ($jsonArray && 0 == $jsonArray->code) {
            return true;
        }

        return false;
    }

    public static function sendMessage2($mobile, $message)
    {
        $urlTemplate = "http://tscm2.800ct.com:9002/MWGate/wmgw.asmx/MongateCsSpSendSmsNew?userId=J02282&password=588620&pszMobis=%s&pszMsg=%s&iMobiCount=1&pszSubPort=*";
        $content = rawurlencode($message);
        $serverUrl = sprintf($urlTemplate, (string)$mobile, $content);
        $sl = HttpFunction::getPage($serverUrl, 5, false);
        if ($sl && strlen(abs(strip_tags($sl))) > 6) {
            return true;
        } else {
            return false;
        }
    }

    /**
     *  短信发送方法
     *
     * @author liang<lang@vip.deyi.com>
     * @param $phone
     * @param $message
     * @return bool
     */
    public static function send($phone, $message)
    {
        if (self::sendMessage2($phone, $message)) {
            return true;
        }

        return self::sendMessage($phone, $message);
    }
}
